﻿using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour {

	public float health = 100;
	public float maxHealth = 100;
	public GameObject explosionPrefab;

	public TriggerArea triggerArea;
	public Shooter shooter;
	public float attackCooldown = 1;
	private float currentAttackCoolDown = 0;

	public EnemyFollow ef;
	
	void Start()
	{
		health = maxHealth;
	}

	void Update () 
	{
		gameObject.renderer.material.color = Color.Lerp (Color.red, Color.green, health / maxHealth);

		ef.target = triggerArea.target;
		if (triggerArea.target!=null)
		{
			transform.LookAt(triggerArea.target);

			currentAttackCoolDown+=Time.deltaTime;

			if (currentAttackCoolDown>=attackCooldown)
			{
				currentAttackCoolDown = 0;
				shooter.Shoot(rigidbody.velocity);
			}
		}
	}

	void OnCollisionEnter(Collision coll)
	{
		if (coll.gameObject.tag.Equals("Projectile"))
		{
			health -= 5;

			if (health<=0)
			{
				GameObject.Instantiate(explosionPrefab, transform.position, transform.rotation);
				Destroy(gameObject);
			}
		}
	}
}
